package org.csu.mypetstore.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.csu.mypetstore.domain.BO.OrderBO;
import org.csu.mypetstore.domain.BO.OrderListInfo;
import org.csu.mypetstore.domain.PO.*;
import org.csu.mypetstore.mapper.*;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SequenceMapper sequenceMapper;
    @Autowired
    private LineItemMapper lineItemMapper;
    @Autowired
    private InventoryMapper inventoryMapper;
    @Autowired
    private OrderStatusMapper orderStatusMapper;
    private QueryWrapper<OrderStatus>orderStatusQueryWrapper;
    private QueryWrapper<Order>orderQueryWrapper;
    private QueryWrapper<LineItem>lineItemQueryWrapper;
    private QueryWrapper<Sequence>sequenceQueryWrapper;
    private UpdateWrapper<Sequence>sequenceUpdateWrapper;
    private QueryWrapper<Inventory>inventoryQueryWrapper;

    private Order getOrderFromOrderBO(OrderBO orderBO){
        Order order = new Order();
        BeanUtils.copyProperties(orderBO, order);//快速赋值
        return order;
    }

    private OrderBO getOrderBOByOrderAndLineItemList(Order order, List<LineItem> lineItems){
        OrderBO orderBO = new OrderBO();
        BeanUtils.copyProperties(order, orderBO);
        orderBO.setLineItems(lineItems);
        return orderBO;
    }


    public OrderServiceImpl(){
        orderQueryWrapper = new QueryWrapper<>();
        orderStatusQueryWrapper = new QueryWrapper<>();
        lineItemQueryWrapper = new QueryWrapper<>();
        sequenceQueryWrapper = new QueryWrapper<>();
        sequenceUpdateWrapper = new UpdateWrapper<>();
        inventoryQueryWrapper = new QueryWrapper<>();
    }

    @Override
    public void insertOrder(OrderBO orderBO) {
        Inventory inventory = new Inventory();
        orderBO.setOrderId(getNextId("ordernum"));
        //更新inventory数据库
        for (int i = 0; i < orderBO.getLineItems().size(); i++) {
            LineItem lineItem = orderBO.getLineItems().get(i);
            String itemId = lineItem.getItemId();
            Integer increment = new Integer(lineItem.getQuantity());
            //通过itemId找到现在的库存，并减去订单的内容
            //TODO 多次查询数据库是否有事务问题以及效率问题
            inventoryQueryWrapper.clear();
            inventoryQueryWrapper.eq("itemId", lineItem.getItemId());
            BigDecimal nowQuantity = inventoryMapper.selectOne(inventoryQueryWrapper).getQuantity().subtract(BigDecimal.valueOf(increment));
            inventory.setQuantity(nowQuantity);
            //更新Inventory库存数量
            inventory.setItemId(itemId);
            UpdateWrapper<Inventory> inventoryUpdateWrapper = new UpdateWrapper<>();
            inventoryUpdateWrapper.eq("itemId",itemId);
            inventoryMapper.update(inventory,inventoryUpdateWrapper);
        }

        OrderStatus orderStatus = new OrderStatus();
        //将OrderStatus更新到数据库中
        orderMapper.insert(getOrderFromOrderBO(orderBO));
        orderStatus.setOrderId(orderBO.getOrderId());
        orderStatus.setLinenum(orderBO.getLineItems().size());
        orderStatus.setTimestamp(new Date());
        orderStatus.setStatus("P");
        orderStatusMapper.insert(orderStatus);

        //插入lineitem的数据库
        for (int i = 0; i < orderBO.getLineItems().size(); i++) {
            LineItem lineItem = orderBO.getLineItems().get(i);
            lineItem.setOrderId(orderBO.getOrderId());
            lineItemMapper.insert(lineItem);
            System.out.println("lineItem----插入成功");
        }
    }

    @Override
    public OrderBO getOrderBO(int orderId) {
        //设置条件构造器
        orderQueryWrapper.clear();
        orderQueryWrapper.eq("orderId",orderId);
        Order order = orderMapper.selectOne(orderQueryWrapper);
        
        if (order == null)
            return null;

        lineItemQueryWrapper.clear();
        lineItemQueryWrapper.eq("orderId",orderId);
        //设置订单的栏位
        OrderBO orderBO = getOrderBOByOrderAndLineItemList(order, lineItemMapper.selectList(lineItemQueryWrapper));
        return orderBO;
    }

    //通过用户名获取订单列表 test pass
    public List<OrderListInfo> getOrdersByUsername(String username) {
        orderQueryWrapper.clear();
        orderQueryWrapper.eq("username",username);
        List<Order>orderList =  orderMapper.selectList(orderQueryWrapper);
        Iterator<Order>iterator = orderList.listIterator();
        List<OrderListInfo> newOrderList = new ArrayList<>();
        //设置每个订单的状态
        while(iterator.hasNext()){
            orderStatusQueryWrapper.clear();
            Order order = iterator.next();
            orderStatusQueryWrapper.eq("orderId",order.getOrderId());
            OrderListInfo newOrder = new OrderListInfo();
            newOrder.setOrderId(order.getOrderId());
            newOrder.setOrderDate(order.getOrderDate());
            newOrder.setTotalPrice(order.getTotalPrice());
            newOrderList.add(newOrder);
        }
//        return orderList;
        return newOrderList;
    }

    //获取下一行
    public int getNextId(String name) {
        Sequence sequence = new Sequence(name, -1);
        sequenceQueryWrapper.clear();
        sequenceQueryWrapper.eq("name",name);
        sequence = sequenceMapper.selectOne(sequenceQueryWrapper);
        if (sequence == null) {
            throw new RuntimeException("Error: A null sequence was returned from the database (could not get next " + name
                    + " sequence).");
        }
        Sequence parameterObject = new Sequence(name, sequence.getNextId() + 1);
        sequenceUpdateWrapper.clear();
        sequenceUpdateWrapper.eq("name",name);
        sequenceMapper.update(parameterObject,sequenceUpdateWrapper);
        return sequence.getNextId();
    }


//    //找出当前所有的order
//    public List<Order> getAllAccountOrder(){
//        //从order表中取出所有的orderId赋值给orderIdlist
//        QueryWrapper<Order>orderQueryWrapper = new QueryWrapper<>();
//        orderQueryWrapper.select("orderId");
//        List<Order>orderIdList = orderMapper.selectList(orderQueryWrapper);
//        List<Order>orderList = new ArrayList<>();
//        //给order赋值
//        Iterator<Order>orderIterator = orderIdList.listIterator();
//        while(orderIterator.hasNext()){
//            orderList.add(getOrder(orderIterator.next().getOrderId()));
//        }
//        return orderList;
//    }
//
//
//    //删除该订单，并向该订单的用户发送一条消息，保存在数据库中存储，message是发送给用户信息
//    public void adminDeleteOrder(int orderId , String username , String message){
//        //删除该订单
//        deleteOrder(orderId);
//        //向account_message表中插入已经删除订单的信息
//        Accountmessage accountmessage = new Accountmessage();
//        accountmessage.setInfo(message);
//        accountmessage.setUsername(username);
//        accountmessageMapper.insert(accountmessage);
//    }
//
//    //发货，并向该订单的用户发送一条消息，保存在数据库中存储，message是发送给用户信息
//    public void adminSendOrder(int orderId,String userid,String message){
//        //删除该订单
//        deleteOrder(orderId);
//        //向account_message表中插入已经发货的订单信息
//        Accountmessage accountmessage = new Accountmessage();
//        accountmessage.setUsername(userid);
//        accountmessage.setInfo(message);
//        accountmessageMapper.insert(accountmessage);
//    }
//
//    //通过username获取发送给用户的所有信息内容（返回accountmessage的list对象）
//    public List<Accountmessage> getMsgByUsername(String username){
//        accountmessageQueryWrapper.clear();
//        accountmessageQueryWrapper.eq("username",username);
//        return accountmessageMapper.selectList(accountmessageQueryWrapper);
//    }
//
//    //通过orderId删除订单
//    private void deleteOrder(int orderId){
//        //删除order表中的该订单
//        orderQueryWrapper.clear();
//        orderQueryWrapper.eq("orderId",orderId);
//        orderMapper.delete(orderQueryWrapper);
//        //删除lineitem表中的该订单
//        lineItemQueryWrapper.clear();
//        lineItemQueryWrapper.eq("orderId",orderId);
//        lineItemMapper.delete(lineItemQueryWrapper);
//        //删除orderstatus表中的该订单
//        orderStatusQueryWrapper.clear();
//        orderStatusQueryWrapper.eq("orderId",orderId);
//        orderStatusMapper.delete(orderStatusQueryWrapper);
//    }



}

